/**
 * 
 */
package cn.jhz.filesharingsystem.util;

import java.io.IOException;

import javax.annotation.PostConstruct;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author asus
 *
 */
@Component
public class LuceneUtil {
	@Autowired
	private IndexWriter indexWriter;
	@SuppressWarnings("unused")
	@Autowired
	private Directory directory;
	@Autowired
	private IndexReader indexReader;
	@Autowired
	private Analyzer analyzer;
	
	public LuceneUtil() {
		
	}
	
	public static LuceneUtil luceneUtil;
	
	@PostConstruct
	public void init() {
		luceneUtil = this;
	}
	
	static public IndexWriter getIndexWriter() {
		return luceneUtil.indexWriter;
	}
	static public IndexSearcher getSearcher() throws IOException {
		IndexReader temp = DirectoryReader.openIfChanged((DirectoryReader) luceneUtil.indexReader, luceneUtil.indexWriter, true);
		if(temp != null) 
			luceneUtil.indexReader = temp;
		return new IndexSearcher(luceneUtil.indexReader);
	}
	static public QueryParser getQueryParser() {
		return new MultiFieldQueryParser(new String[]{"fileName","size","type","provider","notes"}, luceneUtil.analyzer);
	}
	static public Highlighter getHighlighter(Query query, int size) {
		//格式器，通过格式器指定怎样对关键字进行处理  
		Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
		//通过Scorer包装query实例
		Scorer fragmentScorer = new QueryScorer(query);
		//创建高亮器
		Highlighter highlighter = new Highlighter(formatter, fragmentScorer);
		//创建格式化片段
		Fragmenter fragmenter = new SimpleFragmenter(size);
		//将格式化片段实例与高亮器关联      因为最终是通过 高亮器Highlighter对文本信息进行处理
		highlighter.setTextFragmenter(fragmenter);
		return highlighter;
	}
	static public Analyzer getAnalyzer() {
		return luceneUtil.analyzer;
	}
	static public void closeIndexWriter() throws IOException {
		luceneUtil.indexWriter.close();
	}
	static public void closeIndexReader() throws IOException {
		luceneUtil.indexReader.close();
	}
	
}
